
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <title>JSON</title>
</head>
<body>
    <script>
        'use strict';
        // 1. 序列化
        var xiaoming = {
            name: '小明',
            age: 14,
            gender: true,
            height: 1.65,
            grade: null,
            'middle-school': '\"W3C\" Middle School',
            skills: ['JavaScript', 'Java', 'Python', 'Lisp'],
            
        };

        var s = JSON.stringify(xiaoming, null, '  ');
        console.log(s);
        console.log("=======================");
        console.log(JSON.stringify(xiaoming,['name','skills'],'  '));
        console.log("=======================");

        function convert(key,value) {
            if (typeof value === 'string') {
                return value.toUpperCase();
            }
            return value;
        }

        console.log(JSON.stringify(xiaoming,convert,'  '));
        console.log("=======================");

        var xiaoming2 = {
            name: '小明',
            age: 14,
            gender: true,
            height: 1.65,
            grade: null,
            'middle-school': '\"W3C\" Middle School',
            skills: ['JavaScript', 'Java', 'Python', 'Lisp'],
            toJSON: function(){
                return {  // 只输出name和age，并且改变了key：
                    'Name': this.name,
                    'Age': this.age
                };
            }
        };
        
        console.log(JSON.stringify(xiaoming2)); // '{"Name":"小明","Age":14}'

        // 2. 反序列化
        // 拿到一个JSON格式的字符串，我们直接用JSON.parse()把它变成一个JavaScript对象
        JSON.parse('[1,2,3,true]'); // [1, 2, 3, true]
        JSON.parse('{"name":"小明","age":14}'); // Object {name: '小明', age: 14}
        JSON.parse('true'); // true
        JSON.parse('123.45'); // 123.45

        var obj = JSON.parse('{"name":"小明","age":14}', function (key, value) {
            if (key === 'name') {
                return value + '同学';
            }
            return value;
        });
        console.log(JSON.stringify(obj)); // {name: '小明同学', age: 14}
        
        // 练习
        // 用浏览器访问OpenWeatherMap的天气API，查看返回的JSON数据，然后返回城市、天气预报等信息
        var url = 'https://api.openweathermap.org/data/2.5/forecast?q=Beijing,cn&appid=800f49846586c3ba6e7052cfc89af16c';
        $.getJSON(url, function (data) {
            var info = {
                city: data.city.name,
                weather: data.list[0].weather[0].main,
                time: data.list[0].dt_txt
            };
            alert(JSON.stringify(info, null, '  '));
        });
    </script>
</body>
</html>